package cn.caskm.souvenirshopsystem.controller.common;

import cn.caskm.souvenirshopsystem.config.FileProperties;
import cn.caskm.souvenirshopsystem.domain.Result;
import cn.caskm.souvenirshopsystem.exceptions.BizException;
import cn.hutool.core.lang.UUID;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

@RestController
@RequestMapping("/file")
@RequiredArgsConstructor
public class FileController {

    private final FileProperties fileProperties;

    @PostMapping("/uploadImage/{prefix}")
    public Result<String> uploadImage(@PathVariable("prefix") String prefix, MultipartFile file) throws IOException {
        if (file == null || file.isEmpty()) {
            throw new BizException("文件为空");
        }

        // 获取原始文件名和后缀名
        String originalFilename = file.getOriginalFilename();
        String suffix = "";
        if (originalFilename != null && originalFilename.contains(".")) {
            suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        }

        // 生成文件名
        String fileName = UUID.fastUUID().toString(true) + suffix;

        // 创建文件夹
        File targetFileDir = new File(fileProperties.getBaseDir() + File.separator + prefix);
        if (!targetFileDir.exists()) {
            boolean ifSuccess = targetFileDir.mkdirs();
            if (!ifSuccess) {
                throw new BizException("文件夹创建失败");
            }
        }

        // 创建文件并保存文件
        File targetFile = new File(targetFileDir + File.separator + fileName);
        file.transferTo(targetFile);
        return Result.success(prefix + "/" + fileName);
    }

    @GetMapping("/download")
    public void download(@RequestParam("fileName") String fileName, HttpServletResponse response) throws IOException {
        try (BufferedOutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
             BufferedInputStream inputStream = new BufferedInputStream(
                     Files.newInputStream(Paths.get(fileProperties.getBaseDir() + "/" + fileName)))) {
            byte[] buffer = new byte[10240];
            int len;
            while ((len = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, len);
                outputStream.flush();
            }
        }
    }

}
